package net.j4love.dubbo.serialize;

import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author He Peng
 * @create 2017-05-29 1:52
 * @update 2017-05-29 1:52
 * @updatedesc : 更新说明
 * @see
 */
public class FstSerialize {

    private static FSTConfiguration fstConf;

    static {
        fstConf = FSTConfiguration.createDefaultConfiguration();
    }



    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student student = new Student();
        List<Hobby> hobbies = new ArrayList<>();
        hobbies.add(new Hobby().setDesc("学英语"));
        hobbies.add(new Hobby().setDesc("玩游戏"));
        hobbies.add(new Hobby().setDesc("打篮球"));
        hobbies.add(new Hobby().setDesc("吐槽"));

        student.setName("小明")
                .setAge(12)
                .setGender("男")
                .setHobbies(hobbies);

        byte[] bytes = serialize(student);
        System.err.println("byte size : " + bytes.length); // 148

        Object object = deserialize(bytes);
        if (object.equals(student)) {
            System.err.println(object);
        }
    }

    public static byte[] serialize(Object obj) throws IOException {
        FSTObjectOutput objectOutput = fstConf.getObjectOutput();
        objectOutput.writeObject(obj);
        return objectOutput.getCopyOfWrittenBuffer();
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        FSTObjectInput objectInput = fstConf.getObjectInput(bytes);
        return objectInput.readObject();
    }
}
